import { WS_SEND_DATA } from '../middleware/ws'
import { formatValue } from '../../utils/dataUtils'
import { TRADE_BID_ASK_ACTION } from '../reducers/tradeBidAskReducer'
import { fromJS } from 'immutable'

export function subscribeDepth (contract) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '1',
            LocalNo: 5,
            TopicID: '8',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}`,
            ResumeNo: -2
          }
        }
      })
    }
  }
}

export function unsubscribeDepth (contract) {
  return dispatch => {
    if (contract) {
      dispatch({
        type: WS_SEND_DATA,
        data: {
          SendTopicAction: {
            Action: '2',
            LocalNo: 5,
            TopicID: '8',
            FilterValue: `${formatValue(contract, 'ExchangeID')}_${formatValue(contract, 'InstrumentID')}`,
            ResumeNo: -2
          }
        }
      })
    }
  }
}

let pollBidAskEnabled = true
export function setPollBidAskEnabled (enabled) {
  pollBidAskEnabled = enabled
}

function pollBidAsk (dispatch, getState) {
  setTimeout(() => {
    if (pollBidAskEnabled) {
      const totalBid = getState().trade.bidAsk.get('totalBid')
      const totalAsk = getState().trade.bidAsk.get('totalAsk')

      const bidPriceKeys = Object.keys(totalBid.toJS())
      bidPriceKeys.sort((v1, v2) => {
        return v2.split('_')[2] - v1.split('_')[2]
      })
      if (bidPriceKeys.length > 30) {
        bidPriceKeys.splice(30, bidPriceKeys.length - 30)
      }

      const askPriceKeys = Object.keys(totalAsk.toJS())
      askPriceKeys.sort((v1, v2) => {
        return v1.split('_')[2] - v2.split('_')[2]
      })
      if (askPriceKeys.length > 30) {
        askPriceKeys.splice(30, askPriceKeys.length - 30)
      }
      const bidList = []
      bidPriceKeys.forEach(key => {
        bidList.push(totalBid.get(key))
      })
      const askList = []
      askPriceKeys.forEach(key => {
        askList.push(totalAsk.get(key))
      })
      dispatch({
        type: TRADE_BID_ASK_ACTION,
        data: {
          bidList: fromJS(bidList),
          askList: fromJS(askList)
        }
      })
      pollBidAsk(dispatch, getState)
    }
  }, 200)
}

export function getBidAsk () {
  setPollBidAskEnabled(true)
  return (dispatch, getState) => {
    pollBidAsk(dispatch, getState)
  }
}
